package com.lsl.endworkvol.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.lsl.endworkvol.entity.Leader;
import com.lsl.endworkvol.entity.Volunteer;
import com.lsl.endworkvol.service.LeaderService;
import com.lsl.endworkvol.service.VolunteerService;

@Controller
public class UserManagementController {

    @Autowired
    private VolunteerService volunteerService;

    @Autowired
    private LeaderService leaderService;

    @RequestMapping(path = "admin/user_manager/volunteer", method = RequestMethod.GET)
    public ModelAndView toVolunteerList(ModelAndView modelAndView) {
        modelAndView.setViewName("admin/user_volunteer_manager");
        @SuppressWarnings("unchecked") 
        List<Volunteer> volunteers = (List<Volunteer>)volunteerService.getUsers();
        modelAndView.addObject("userList", volunteers);
        return modelAndView;
    }

    @RequestMapping(path = "admin/user_manager/leader", method = RequestMethod.GET)
    public ModelAndView toLeaderList(ModelAndView modelAndView) {
        modelAndView.setViewName("admin/user_leader_manager");
        @SuppressWarnings("unchecked")
        List<Leader> leaders = (List<Leader>)leaderService.getUsers();
        modelAndView.addObject("userList", leaders);
        return modelAndView;
    }

    @RequestMapping(path = "admin/user_create_page", method = RequestMethod.GET)
    public ModelAndView toCreateUserPage(ModelAndView modelAndView) {
        modelAndView.setViewName("admin/user_add");
        return modelAndView;
    }

    @RequestMapping(path = "admin/user_create", method = RequestMethod.POST)
    public String createUser(@RequestParam Map<String,String> params) {
        boolean flag = false;
        if (params.get("role").equals("0")) {
            int createCount = Integer.parseInt(
                params.getOrDefault("create_count", "") == "" ? "1" : params.get("create_count")
            );
            for (int i = 0; i < createCount; i++) {
                int indexInLambda = i + 1;
                flag = volunteerService.addUser(() -> {
                    Volunteer volunteer = new Volunteer();
                    volunteer.setVolId(String.valueOf(
                        Integer.parseInt(
                            params.get("vol_id") == "" ? "0" : params.get("vol_id")
                        ) + (indexInLambda - 1)
                    ));
                    if (createCount == 1) {
                        volunteer.setName(params.getOrDefault("username", ""));
                    } else {
                        volunteer.setName(params.getOrDefault("username", "") + indexInLambda);
                    }
                    volunteer.setPassword(params.getOrDefault("password", ""));
                    return volunteer;
                });
                if (!flag) return "redirect:/admin/warning/create_user_failed"; 
            }
        } else if (params.get("role").equals("1")) {
            int createCount = Integer.parseInt(
                params.getOrDefault("create_count", "") == "" ? "1" : params.get("create_count")
            );
            for (int i = 0; i < createCount; i++) {
                int indexInLambda = i + 1;
                flag = leaderService.addUser(() -> {
                    Leader leader = new Leader();
                    if (createCount == 1) {
                        leader.setUsername(params.getOrDefault("username", ""));
                    } else {
                        leader.setUsername(params.getOrDefault("username", "") + indexInLambda);
                    }
                    leader.setPassword(params.getOrDefault("password", ""));
                    return leader;
                });
                if (!flag) return "redirect:/admin/warning/create_user_failed"; 
            }
        } else {
            return "redirect:/admin/warning/create_user_failed_unknow_role";
        }
        return "redirect:/admin/warning/create_user_success";
    }

    @RequestMapping(path = "admin/user_search/volunteer", method = RequestMethod.POST)
    public ModelAndView VolunteerSearch(@RequestParam Map<String,String> params, ModelAndView modelAndView) {
        modelAndView.setViewName("admin/user_volunteer_manager");
        @SuppressWarnings("unchecked")
        List<Volunteer> userList = (List<Volunteer>)volunteerService.getUsers(() -> {
            Volunteer volunteer = new Volunteer();
            volunteer.setName(params.getOrDefault("username", ""));
            volunteer.setVolId(params.getOrDefault("vol_id" ,""));
            volunteer.setSex(params.getOrDefault("sex", ""));
            volunteer.setMajorclass(params.getOrDefault("majorclass", ""));
            return volunteer;
        });
        modelAndView.addObject("userList", userList);
        return modelAndView;
    }

    @RequestMapping(path = "admin/user_search/leader", method = RequestMethod.POST)
    public ModelAndView LeaderSearch(@RequestParam Map<String,String> params, ModelAndView modelAndView) {
        modelAndView.setViewName("admin/user_leader_manager");
        @SuppressWarnings("unchecked")
        List<Leader> userList = (List<Leader>)leaderService.getUsers(() -> {
            Leader leader = new Leader();
            leader.setUsername((params.getOrDefault("username", "")));
            leader.setPhone(params.getOrDefault("phone", ""));
            leader.setEmail(params.getOrDefault("email", ""));
            return leader;
        });
        modelAndView.addObject("userList", userList);
        return modelAndView;
    }

    @RequestMapping(path = "admin/user_info_reset/volunteer/{id}", method = RequestMethod.GET)
    public String VolunteerInfoReset(@PathVariable String id) {
        boolean flag = volunteerService.editUser(() -> {
            Volunteer volunteer = new Volunteer();
            volunteer.setId(Integer.parseInt(id));
            volunteer.setName(null);
            return volunteer;
        });
        if (flag) {
            return "redirect:/admin/message/volunteer_info_reset_success";
        } else {
            return "redirect:/admin/warning/volunteer_info_reset_failed";
        }
    }

    @RequestMapping(path = "admin/user_info_reset/leader/{id}", method = RequestMethod.GET)
    public String LeaderInfoReset(@PathVariable String id) {
        boolean flag = leaderService.editUser(() -> {
            Leader leader = new Leader();
            leader.setId(Integer.parseInt(id));
            leader.setUsername(null);
            return leader;
        });
        if (flag) {
            return "redirect:/admin/message/leader_info_reset_success";
        } else {
            return "redirect:/admin/warning/leader_info_reset_failed";
        }
    }

    @RequestMapping(path = "admin/user_pwd_reset/volunteer/{id}", method = RequestMethod.GET)
    public String VolunteerPasswordReset(@PathVariable String id, @RequestParam Map<String,String> params) {
        boolean flag = volunteerService.editUser(() -> {
            Volunteer volunteer = (Volunteer)volunteerService.getUser(Integer.parseInt(id));
            volunteer.setPassword("123456");    
            return volunteer;
        });
        if (flag) {
            return "redirect:/admin/message/volunteer_pwd_reset_success";
        } else {
            return "redirect:/admin/warning/volunteer_pwd_reset_failed";
        }
    }

    @RequestMapping(path = "admin/user_pwd_reset/leader/{id}", method = RequestMethod.GET)
    public String LeaderPasswordReset(@PathVariable String id, @RequestParam Map<String,String> params) {
        boolean flag = leaderService.editUser(() -> {
            Leader leader = (Leader)leaderService.getUser(Integer.parseInt(id));
            leader.setPassword("123456");
            return leader;
        });
        if (flag) {
            return "redirect:/admin/message/leader_pwd_reset_success";
        } else {
            return "redirect:/admin/warning/leader_pwd_reset_failed";
        }
    }

    @RequestMapping(path = "admin/user_delete/volunteer/{id}", method = RequestMethod.GET)
    public String VolunteerDelete(@PathVariable String id) {
        boolean flag = volunteerService.deleteUser(Integer.parseInt(id));
        if (flag) {
            return "redirect:/admin/message/volunteer_delete_success";
        } else {
            return "redirect:/admin/warning/volunteer_delete_failed";
        }
    }

    @RequestMapping(path = "admin/user_delete/leader/{id}", method = RequestMethod.GET)
    public String LeaderDelete(@PathVariable String id) {
        boolean flag = leaderService.deleteUser(Integer.parseInt(id));
        if (flag) {
            return "redirect:/admin/message/leader_delete_success";
        } else {
            return "redirect:/admin/warning/leader_delete_failed";
        }
    }


}